import numpy as np
from numerical_integration.trapezoidal import composite_trapezoidal
from numerical_integration.romberg import romberg_integration
import argparse

# 被积函数
def f(x):
    return np.sqrt(x) * np.log(x)

def main():
    # 参数解析
    parser = argparse.ArgumentParser(description='数值积分参数设置')
    parser.add_argument('--a', type=float, required=True, help='积分下限')
    parser.add_argument('--b', type=float, required=True, help='积分上限')
    parser.add_argument('--epsilon', type=float, default=1e-5, help='误差阈值（默认：1e-5）')

    args = parser.parse_args()

    a = args.a
    b = args.b
    epsilon = args.epsilon

    # 使用复化梯形公式
    result_trapezoid, n_trapezoid = composite_trapezoidal(a, b, f, epsilon)
    step_size_trapezoid = (b - a) / n_trapezoid
    
    # 打印结果
    print(f"复化梯形公式结果: {result_trapezoid}, 划分次数: {int(np.log2(n_trapezoid))}, 步长: {step_size_trapezoid}")
    
    # 使用龙贝格算法
    result_romberg, n_romberg = romberg_integration(a, b, f, epsilon)
    step_size_romberg = (b - a) / (2 ** (n_romberg - 1))  # 在这里计算步长
    
    # 打印结果
    print(f"龙贝格算法结果: {result_romberg}, 划分次数: {int(np.log2(n_romberg))}, 步长: {step_size_romberg}")

    # 将结果写入 output.csv
    with open("output.csv", "a") as f_out:
        f_out.write(f"{a},{b},{epsilon},{result_trapezoid},{n_trapezoid},{step_size_trapezoid},复化梯形公式\n")
        f_out.write(f"{a},{b},{epsilon},{result_romberg},{n_romberg},{step_size_romberg},龙贝格算法\n")

if __name__ == "__main__":
    main()
